package cn.taobaoke.restful.controller;

import cn.taobaoke.restful.exception.TBKException;
import cn.taobaoke.restful.service.InviteCodeService;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/invitecodes")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class InviteCodeController extends BaseController {

    @GetMapping("")
    public Result queryInviteCodeByCode(@RequestParam String code) {
        return wrapObj(inviteCodeService.findByCode(code));
    }

    @PostMapping("")
    public Result consumeInviteCode(@RequestBody Map<String, Object> map) {
        if (!map.containsKey("agentId"))
            throw new TBKException("缺少参数，代理ID");
        if (!map.containsKey("code")) {
            throw new TBKException("缺少参数，邀请码");
        }
        Long agentId = (Long) map.get("agentId");
        String code = (String) map.get("code");
        return wrapObj(inviteCodeService.consumeCode(agentId, code));
    }

    private final @NonNull
    InviteCodeService inviteCodeService;
}
